<?php

namespace app\cashier\controller;

use app\common\controller\Frontend;
use fast\Random;
use think\Db;
use think\Exception;
use think\Session;

/**
 * 会员中心
 */
class Cashier extends Frontend
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    public function _initialize()
    {
        // Session::set('shop',1);
        $this->shop_id = 1;//Session::get('shop',1);
    }

    public function index()
    {
        $limit = 15;
        $page = 1;
        if (true === $this->request->isAjax()) {
            $page = $this->request->param('page');
            $id = $this->request->param('id');
            $type = $this->request->param('type');
            $list = [];
            if ($type == 'good') {
                if (empty($id)) {
                    $id = 106;
                }

                $category = Db::name('wanlshop_category')->field('id,pid,name')->where('pid', 104)->where('status', 'normal')->select();
                $list = Db::name('wanlshop_goods')
                    ->field('id,image,title,price')
                    ->where('shop_id', $this->shop_id)
                    ->where('category_id', $id)
                    ->where('status', 'normal')
                    ->paginate($limit, false, ['page' => $page])
                    ->each(function ($v) {
                        $v['image'] = get_img($v['image']);
                        return $v;
                    })->toArray();
                $data = [
                    'category' => $category,
                    'list'     => $list
                ];
            }
            if ($type == 'service') {
                if (empty($id)) {
                    $id = 108;
                }
                $category = Db::name('wanlshop_category')->field('id,pid,name')->where('pid', 105)->where('status', 'normal')->select();
                $list = Db::name('wanlshop_goods')
                    ->field('id,image,title,price')
                    ->where('shop_id', $this->shop_id)
                    ->where('category_id', $id)
                    ->where('status', 'normal')
                    ->paginate($limit, false, ['page' => $page])
                    ->each(function ($v) {
                        $v['image'] = get_img($v['image']);
                        return $v;
                    })->toArray();
                $data = [
                    'category' => $category,
                    'list'     => $list
                ];
            }
            $shop_id = $this->shop_id;
            if ($type == 'card') {
                if (empty($id)) {
                    $id = 1;
                }
                $category = [
                    //1=有限次卡,2=不限次卡,3=通卡,4=充值卡,5=折扣卡
                    ['id' => 1, 'name' => '有限次卡'],
                    ['id' => 2, 'name' => '不限次卡'],
                    ['id' => 3, 'name' => '通卡'],
                    ['id' => 4, 'name' => '充值卡'],
                    ['id' => 5, 'name' => '折扣卡'],
                ];
                $list = Db::name('item')
                    ->where('type', $id)
                    ->where(function ($query) use ($shop_id) {
                        $query->where('stock', '0')
                            ->whereOr(function ($query) use ($shop_id) {
                                $query->where('stock', '1')
                                    ->whereRaw("FIND_IN_SET($shop_id, shop_ids)");
                            });
                    })
                    ->order('createtime', 'desc')
                    ->paginate($limit, false, ['page' => $page])->each(function (&$v) {
                        if (!isset($v['card_service'])) {
                            $v['card_service'] = '';
                        }
                        if (!isset($v['time'])) {
                            $v['time'] = '';
                        }
                        if (!isset($v['type_name'])) {
                            $v['type_name'] = '';
                        }
                        switch ($v['type']) {
                            case 1:
                                $v['type_name'] = '有限次卡';
                                break;
                            case 2:
                                $v['type_name'] = '不限次卡';
                                break;
                            case 3:
                                $v['type_name'] = '通卡';
                                break;
                            case 4:
                                $v['type_name'] = '充值卡';
                                break;
                            case 5:
                                $v['type_name'] = '折扣卡';
                                break;
                        }
                        if ($v['validity'] == 0) {
                            $v['time'] = '永久有效';
                        }
                        if ($v['validity'] == 1) {
                            $v['time'] = date('Y-m-d', $v['validitytime']);
                        }
                        if ($v['validity'] == 2) {
                            $v['time'] = '购买后' . $v['validitydays'] . '天内有效';
                        }
                        if ($v['validity'] == 3) {
                            $v['time'] = '首次使用后' . $v['validitydays'] . '天内有效';
                        }
                        $ser = Db::name('item_info i')->where('i.item_id', $v['id'])
                            ->join('wanlshop_goods_sku s', 'i.sku_id = s.id', 'left')->select();
                        foreach ($ser as $kk => $vv) {
                            $v['card_service'] .= $vv['difference'] . '、';
                        }
                        return $v;
                    })->toArray();
                $data = [
                    'category' => $category,
                    'list'     => $list
                ];
            }
            return $this->success('', '', $data);
        }
        $category = Db::name('wanlshop_category')->field('id,pid,name')->where('pid', 104)->where('status', 'normal')->select();
        $list = [];
        foreach ($category as $k => $v) {
            $list['category'][$k] = $v;
            $list['category'][$k]['child'] = Db::name('wanlshop_goods')
                ->field('image,title,price')
                ->where('shop_id', $this->shop_id)
                ->where('category_id', $v['id'])
                ->where('status', 'normal')
                ->paginate($limit, false, ['page' => $page])
                ->each(function ($v) {
                    $v['image'] = get_img($v['image']);
                    return $v;
                })->toArray();
        }
        unset($v);
        $this->view->assign('category', $category);
        $this->view->assign('list', $list);
        return $this->view->fetch();
    }

    public function specifications()
    {
        $id = $this->request->param('id');
        $good = Db::name('wanlshop_goods')->where('id', $id)->find();
        $good['image'] = get_img($good['image']);
        $row = Db::name('wanlshop_goods_sku')->where('goods_id', $id)->where('state', 0)->select();
//        var_dump($good);
        $this->view->assign('good', $good);
        $this->view->assign('list', $row);
        return $this->view->fetch();
    }

    public function choosecard()
    {
        $uid = 1;
        $id = $this->request->param('id');
        $cardid = $this->request->param('cardid');
        $skuid = $this->request->param('skuid');
        $num = $this->request->param('num');
        $price = $this->request->param('price');
        $list = DB::name('wanlshop_order_item')->alias('i')
           // ->field('')
            ->where(['i.user_id' => $uid, 'in.sku_id' => $skuid])
            ->where([]) // 时间
            ->join('wanlshop_order_item_info in', 'i.id = in.order_item_id', 'left')
            ->select();
//        echo '<pre>';
//        var_dump($list);
//        echo '</pre>';
        foreach ($list as $k => &$v){
            $v['is_buy'] = 1;
            if (!isset($v['card_service'])) {
                $v['card_service'] = '';
            }
            if ($v['validitytime'] == 9999){
                $v['time'] = '永久有效';
            }else{
                $v['time'] = date('Y-m-d', $v['validitytime']).'前有效';
            }
            $v['checknum'] = 0;
            if (!isset($v['type_name'])) {
                $v['type_name'] = '';
            }
            switch ($v['type']) {
                case 1:
                    $v['type_name'] = '有限次卡';
                    break;
                case 2:
                    $v['type_name'] = '不限次卡';
                    break;
                case 3:
                    $v['type_name'] = '通卡';
                    break;
                case 4:
                    $v['type_name'] = '充值卡';
                    break;
                case 5:
                    $v['type_name'] = '折扣卡';
                    break;
            }
            $ser = Db::name('wanlshop_order_item_info i')->where('i.item_id', $v['item_id'])->where('i.order_id', $v['order_id'])
                ->join('wanlshop_goods_sku s', 'i.sku_id = s.id', 'left')
                ->select();

            foreach ($ser as $k2 => $v2) {
                $v['card_service'] .= $v2['difference'] . '、';
            }
        }
        unset($v);
//        $data = [];
//        if (!empty($cardid)){
//            $cardid = explode(',',$cardid);
//            foreach ($cardid as $k => $v){
//               $res = DB::name('item')->alias('i')
//                    // ->field('')
//                    ->where(['i.id' => $v, 'in.sku_id' => $skuid])
//                    ->where([]) // 时间
//                    ->join('item_info in', 'i.id = in.item_id', 'left')
//                    ->select();
//               foreach($res as $k1 => &$v1){
//                   if (!isset($v['card_service'])) {
//                       $v1['card_service'] = '';
//                   }
//                   if ($v1['validity'] == 0) {
//                       $v1['time'] = '永久有效';
//                   }
//                   if ($v1['validity'] == 1) {
//                       $v1['time'] = date('Y-m-d', $v1['validitytime']);
//                   }
//                   if ($v1['validity'] == 2) {
//                       $v1['time'] = '购买后' . $v1['validitydays'] . '天内有效';
//                   }
//                   if ($v1['validity'] == 3) {
//                       $v1['time'] = '首次使用后' . $v1['validitydays'] . '天内有效';
//                   }
//                   if (!isset($v1['type_name'])) {
//                       $v1['type_name'] = '';
//                   }
//                   switch ($v1['type']) {
//                       case 1:
//                           $v1['type_name'] = '有限次卡';
//                           break;
//                       case 2:
//                           $v1['type_name'] = '不限次卡';
//                           break;
//                       case 3:
//                           $v1['type_name'] = '通卡';
//                           break;
//                       case 4:
//                           $v1['type_name'] = '充值卡';
//                           break;
//                       case 5:
//                           $v1['type_name'] = '折扣卡';
//                           break;
//                   }
//                   $ser = Db::name('item_info i')->where('i.item_id', $v1['item_id'])
//                       ->join('wanlshop_goods_sku s', 'i.sku_id = s.id', 'left')
//                       ->select();
//                   foreach ($ser as $k3 => $v3) {
//                       $v1['card_service'] .= $v3['difference'] . '、';
//                   }
//                   $v1['spent'] = $v1['total'];
//                   $v1['checknum'] = 0;
//               }
//               if (!empty($res)){
//                   $data[] = $res;
//               }
//            }
//        }
//        unset($v1,$v2,$v3);
//        $reData = [];
//        foreach ($data as $k => $v){
//            foreach ($v as $kk => $vv){
//                $vv['is_buy'] = 0;
//                $reData[] = $vv;
//            }
//        }
//
//       $eedata = array_merge($list,$reData);
       $this->view->assign('list', $list);
        $this->view->assign('num', $num);
        $this->view->assign('price', $price);
       return $this->view->fetch();
      //  var_dump($list);

    }
    public function cardOrder(){
        $uid = 1;
        $data = $this->request->param('data/a');
        // 创建数据
        Db::startTrans();
        try{
            $order_id = Db::name('wanlshop_order')->insertGetId([
                'user_id' => $uid,
                'shop_id' => $this->shop_id,
                'order_no' => create_order_sn($uid),
                'state' => 1,
                'createtime' => time()
            ]);
            foreach ($data as $k => $v){
                $card  =Db::name('item')->where('id', $v['id'])->find();
                if ($v['num'] > 0){
                    for($i = 1; $i <= $v['num']; $i++){
                        $item = [
                            'item_id' => $v['id'],
                            'order_id' => $order_id,
                            'shop_id' => $this->shop_id,
                            'user_id' => $uid,
                            'category_id' => $card['category_id'],
                            'name' => $card['name'],
                            'code' => $card['code'],
                            'consumption' => $card['consumption'],
                            'price' => $card['price'],
                            'specs' => $card['specs'],
                            'image' => $card['image'],
                            'gift'  => $card['gift'],
                            'spent' => $card['total'],
                            'total' => $card['total'],
                            'validity' => $card['validity'],
                            'validitydays' => $card['validitydays'],
                            'shop_ids' => $card['shop_ids'],
                            'stock' => $card['stock'],
                            'activity' => $card['activity'],
                            'distribution' => $card['distribution'],
                            'flag'=> $card['flag'],
                            'activity_type' =>  $card['activity_type'],
                            'status' => 'hidden',
                            'createtime' => time()
                        ];
                        if ($card['validity'] == 0){
                            $item['validitytime'] = 9999;
                        }
                        if ($card['validity'] == 1){
                            $item['validitytime'] = $card['validitytime'];
                        }
                        if ($card['validity'] == 2){
                            $item['validitytime'] = time() + $card['validitydays'] * 24 * 60 * 60;
                        }
                        $item_id =  Db::name('wanlshop_order_item')->insertGetId($item);
                        $sku_list =  Db::name('item_info')->where(['item_id' => $v['id'],])->select();
                        foreach ($sku_list as $kk => $vv){
                            $item_info = [
                                'order_item_id' => $item_id,
                                'item_id' => $v['id'],
                                'order_id' => $order_id,
                                'type' => $vv['type'],
                                'goods_id' => $vv['goods_id'],
                                'sku_id' => $vv['sku_id'],
                                'total' => $vv['total'],
                                'spent' => $vv['total'],
                                'createtime' => time(),
                                'status' => 'hidden'
                            ];
                            Db::name('wanlshop_order_item_info')->insert($item_info);
                        }
                    }
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }
        return $this->success('','',['order_id'=>$order_id]);
    }

    public function add_user(){
        $phone = $this->request->param('phone');
        $phone_pattern = '/^1d{10}$/';
        if (!preg_match('/^1[3-9]\d{9}$/', $phone)){
          return  $this->error('手机号码错误');
        }
       $user =   Db::name('user')->where('mobile',$phone)->find();
       if ($user){
           return  $this->error('该会员已存在');
       }
       Db::startTrans();
        try {
            $ip = request()->ip();
            $time = time();
            $data= [
                'shop_id' => $this->shop_id,
                'nickname'  => preg_match("/^1[3-9]{1}\d{9}$/", $phone) ? substr_replace($phone, '****', 3, 4) : $phone,
                'salt'      => Random::alnum(),
                'jointime'  => $time,
                'joinip'    => $ip,
                'logintime' => $time,
                'mobile'    => $phone,
                'loginip'   => $ip,
                'prevtime'  => $time,
                'status'    => 'normal'
            ];
            $password = 123456;
            $data['password'] = $this->getEncryptPassword($password, $data['salt']);
            Db::name('user')->insert($data);
            Db::commit();
        }catch (Exception $exception){
            Db::rollback();
            return  $this->error('失败');
        }
        return  $this->success('添加成功');

    }
    public function choose_user(){
        $phone = $this->request->param('phone');
        $phone_pattern = '/^1d{10}$/';
        if (!preg_match('/^1[3-9]\d{9}$/', $phone)){
            return  $this->error('手机号码错误');
        }
        $user =   Db::name('user')->where('mobile',$phone)->find();
        if (!$user){
            return  $this->error('该会员不存在');
        }
        return  $this->success('','',$user);
    }
    public function getEncryptPassword($password, $salt = '')
    {
        return md5(md5($password) . $salt);
    }

    public function getcoupon(){
        $phone = $this->request->param('phone');
        $user =   Db::name('user')->where('mobile',$phone)->find();
        if (!$user){
            return  $this->error('该会员不存在');
        }
        $coupon = Db::name('wanlshop_coupon_receive')->where(['shop_id'=>$this->shop_id])->select();
//        $coupon = Db::name('wanlshop_coupon_receive')->where(['shop_id'=>$this->shop_id,'user_id'=>$user['id']])->select();
        return  $this->success('','',$coupon);
    }

    public function choosestaff(){
        $staff  = Db::name('staff')->alias('s')
            ->field('s.*,r.name as rank_name')
            ->where(['s.shop_id'=>$this->shop_id])
            ->join('staff_rank r','r.id = s.rank')->select();
        $this->view->assign('staff', $staff);
        return $this->view->fetch();
    }
    
    public function getstaff(){
        $staff_id = $this->request->param('staff_id');
        $staff  = Db::name('staff')->alias('s')->where('s.id',$staff_id)
            ->field('s.*,r.name as rank_name')->join('staff_rank r','r.id = s.rank')->find();
        return  $this->success('','',$staff);
    }

}
